<template>
  <div class="app-container" v-loading="loading">
    <div class="container_box">
      <el-row>
        <el-col :xs="24" :sm="24" :md="24" :lg="14" :xl="12">
          <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-row>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="費用編碼" prop="costCode">
                  <el-input
                    disabled
                    v-model="form.costCode"
                    placeholder="請輸入費用編碼"
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="費用標題" prop="costTitle">
                  <el-input
                    v-model="form.costTitle"
                    placeholder="請輸入費用標題"
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="費用來源" prop="costSource">
                  <el-select
                    style="width: 100%"
                    v-model="form.costSource"
                    @change="change_costSource"
                    placeholder="請選擇費用來源"
                  >
                    <el-option
                      v-for="dict in dict.type.cost_source"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="支出賬號" prop="costBankNo">
                  <el-input
                    disabled
                    v-model="form.costBankNo"
                    placeholder="請選擇支出賬號"
                  >
                    <el-button
                      slot="append"
                      @click="open_dialog_bank('cost')"
                      icon="el-icon-search"
                    ></el-button>
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="支出銀行" prop="costBankName">
                  <el-input
                    disabled
                    v-model="form.costBankName"
                    placeholder="請輸入支出銀行"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="支出賬戶" prop="costBankAccount">
                  <el-input
                    disabled
                    v-model="form.costBankAccount"
                    placeholder="請輸入支出賬戶"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col
                v-if="form.costSource == 30"
                :xs="24"
                :sm="12"
                :md="12"
                :lg="12"
                :xl="12"
              >
                <el-form-item label="收款人姓名" prop="supplierName">
                  <el-input v-model="form.supplierName"> </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 供應商 -->
            <el-row v-if="form.costSource == 10">
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="供應商編碼" prop="supplierCode">
                  <el-input
                    disabled
                    v-model="form.supplierCode"
                    placeholder="請選擇供應商編碼"
                  >
                    <el-button
                      slot="append"
                      @click="open_dialog_supplierName"
                      icon="el-icon-search"
                    ></el-button>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="供應商名稱" prop="supplierName">
                  <el-input
                    disabled
                    v-model="form.supplierName"
                    placeholder="請輸入供應商名稱"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 收款賬號 -->
            <el-row>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="收款賬號" prop="toBankNo">
                  <el-input
                    disabled
                    v-model="form.toBankNo"
                    placeholder="請選擇收款賬號"
                  >
                    <el-button
                      slot="append"
                      @click="open_dialog_bank('to')"
                      icon="el-icon-search"
                    ></el-button>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="收款銀行" prop="toBankName">
                  <el-input
                    disabled
                    v-model="form.toBankName"
                    placeholder="請輸入收款銀行"
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="收款賬戶" prop="toBankAccount">
                  <el-input
                    disabled
                    v-model="form.toBankAccount"
                    placeholder="請輸入收款賬戶"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="經辦人" prop="operatorName">
                  <el-input
                    disabled
                    v-model="form.operatorName"
                    placeholder="請輸入經辦人"
                  >
                    <el-button
                      slot="append"
                      @click="open_dialog_receiverName"
                      icon="el-icon-search"
                    ></el-button>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="提交時間" prop="submitTime">
                  <el-date-picker
                    style="width: 100%"
                    clearable
                    v-model="form.submitTime"
                    type="date"
                    @input="$forceUpdate()"
                    value-format="yyyy-MM-dd"
                    placeholder="請選擇提交時間"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="稅率" prop="taxRate">
                  <el-input
                    maxlength="4"
                    placeholder="請輸入稅率（0-1）"
                    @change="taxRate_change"
                    oninput="value=value.replace(/^0[0-9]|^[2-9]|^1[0-9]|^1\.|[^\d.]/g,'')"
                    v-model="form.tax"
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="備註" prop="remark">
                  <el-input v-model="form.remark" placeholder="請輸入備註" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>
      <el-row>
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <el-divider content-position="center">費用明細信息</el-divider>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                icon="el-icon-plus"
                size="mini"
                @click="handleAddBizInvoiceItem"
                >添加</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="handleDeleteBizInvoiceItem"
                >删除</el-button
              >
            </el-col>
          </el-row>

          <el-table
            style="width: 100%"
            :data="bizCostItemList"
            :row-class-name="rowItemIndex"
            :row-key="
              (row) => {
                return row.index;
              }
            "
            @selection-change="SelectionChange"
            ref="bizCustomerReservationItem"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column
              label="序號"
              align="center"
              prop="index"
              width="50"
            />
            <el-table-column label="費用事項" prop="costItem" width="150">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.costItem"
                  placeholder="請選擇費用事項"
                  clearable
                >
                  <el-option
                    v-for="dict in dict.type.cost_scope"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="費用金額" align="center" prop="costAmount">
              <template slot-scope="scope">
                <el-input
                  min="0"
                  @change="amountSum(scope.row)"
                  v-model="scope.row.costAmount"
                  placeholder="請輸入費用金額"
                />
              </template>
            </el-table-column>
            <el-table-column label="備註" prop="remark">
              <template slot-scope="scope">
                <el-input v-model="scope.row.remark" placeholder="請輸入備註" />
              </template>
            </el-table-column>
            <el-table-column label="稅金" align="center" prop="taxAmount">
              <template slot-scope="scope">
                <span v-if="scope.row.costAmount">{{
                  scope.row.taxAmount
                }}</span>
                <span v-else>0</span>
              </template>
            </el-table-column>
            <el-table-column
              label="費用含稅金額"
              align="center"
              prop="costTaxAmount"
            >
              <template slot-scope="scope">
                <span v-if="scope.row.costAmount">{{
                  scope.row.costTaxAmount
                }}</span>
                <span v-else>0</span>
              </template>
            </el-table-column>
          </el-table>
          <div style="text-align: center; margin-top: 16px">
            <el-button
              type="primary"
              :disabled="btn_disable"
              @click="submitForm('20')"
              >提 交</el-button
            >
            <el-button
              type="primary"
              :disabled="btn_disable"
              @click="submitForm('10')"
              >保 存</el-button
            >
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-col>
      </el-row>

      <!-- 選擇出賬銀行 -->
      <el-dialog
        :visible.sync="dialog_if_bank"
        destroy-on-close
        :close-on-click-modal="false"
        width="1000px"
        append-to-body
      >
        <bank-table
          :selected="selected_bank_id"
          @out_detail="bank_detail"
          @out_cancel="bank_cancel"
          :type="bank_type"
        >
        </bank-table>
      </el-dialog>
      <!-- 選擇接待人  -->
      <el-dialog
        :visible.sync="dialog_if_receiver"
        destroy-on-close
        :close-on-click-modal="false"
        width="800px"
        append-to-body
      >
        <receiver-table
          :selected="selected_receiver_id"
          @out_detail="receiver_detail"
          @out_cancel="receiver_cancel"
        >
        </receiver-table>
      </el-dialog>
      <!-- 選擇供應商  -->
      <el-dialog
        :visible.sync="dialog_if_supplier"
        destroy-on-close
        :close-on-click-modal="false"
        width="800px"
        append-to-body
      >
        <supplier-table
          :selected="selected_supplier_id"
          @out_detail="supplier_detail"
          @out_cancel="supplier_cancel"
        >
        </supplier-table>
      </el-dialog>
    </div>
  </div>
</template>
      
      <script>
import { getCost, updateCost } from "@/api/biz/cost";
import bankTable from "@/components/biz/bankTable";
import receiverTable from "@/components/biz/receiverTable";
import supplierTable from "@/components/biz/supplierTable";
export default {
  components: { bankTable, receiverTable, supplierTable },
  name: "SupplierAdd",
  dicts: ["cost_source", "bank_type", "cost_scope"],
  data() {
    return {
      btn_disable: false,
      // 表单參數
      form: {
        costSource: "20",
        taxRate: 0,
      },
      // 表单校验
      rules: {},

      // 是否顯示弹出层
      loading: false,
      // 費用明細表格數据
      bizCostItemList: [],
      checkedList: [],

      // 選擇出賬銀行詳細信息
      dialog_if_bank: false,
      selected_bank_id: "",
      selected_bank_id_cost: "",
      selected_bank_id_to: "",
      selected_bank_id_supplie: "",
      selected_bank_id_other: "",
      bank_type: "20",
      // 選擇接待人詳細信息

      dialog_if_receiver: false,
      selected_receiver_id: "",
      // 選擇供應商詳細信息

      dialog_if_supplier: false,
      selected_supplier_id: "",
    };
  },
  created() {
    if (this.$route.query.id) {
      console.log(this.$route.query);
      this.get_detail(this.$route.query.id);
    }
  },
  activated() {
    if (this.$route.query.id) {
      this.get_detail(this.$route.query.id);
    }
  },
  methods: {
    // 獲取詳情
    get_detail(id) {
      getCost(id).then((response) => {
        console.log(response.data);
        this.form.id = response.data.id;

        this.form.costSource = response.data.costSource;
        this.form.costCode = response.data.costCode;
        this.form.costTitle = response.data.costTitle;

        switch (this.form.costSource) {
          case "10":
            this.selected_bank_id_supplie = response.data.toBankId;
            this.form.supplierId = response.data.supplierId;
            this.form.supplierCode = response.data.supplierCode;
            this.form.supplierName = response.data.supplierName;
            break;
          case "20":
            this.selected_bank_id_to = response.data.toBankId;
            break;
          case "30":
            this.selected_bank_id_other = response.data.toBankId;
            this.form.supplierName = response.data.supplierName;
            break;

          default:
            break;
        }
        this.selected_bank_id_cost = response.data.costBankId;
        this.form.costBankId = response.data.costBankId;
        this.form.costBankNo = response.data.costBankNo;
        this.form.costBankName = response.data.costBankName;
        this.form.costBankAccount = response.data.costBankAccount;

        this.form.toBankId = response.data.toBankId;
        this.form.toBankNo = response.data.toBankNo;
        this.form.toBankName = response.data.toBankName;
        this.form.toBankAccount = response.data.toBankAccount;

        this.selected_receiver_id = response.data.operatorId;
        this.form.operatorId = response.data.operatorId;
        this.form.operatorName = response.data.operatorName;

        this.form.costAmount = response.data.costAmount;
        this.form.taxAmount = response.data.taxAmount;
        this.form.costTaxAmount = response.data.costTaxAmount;
        this.form.tax = response.data.tax ? response.data.tax : "0";

        this.form.submitTime = response.data.submitTime;
        this.form.remark = response.data.remark;

        this.bizCostItemList = [];
        response.data.bizCostItemList.map((item) => {
          let obj = {
            costItem: item.costItem,
            costAmount: item.costAmount,
            taxAmount: item.taxAmount,
            costTaxAmount: item.costTaxAmount,
            tax: item.tax,
            quantity: item.quantity,
            uint: item.uint,
            unitPrice: item.unitPrice,
            remark: item.remark,
          };
          this.bizCostItemList.push(obj);
        });
      });
    },

    // 選擇出賬銀行詳細信息----------------------------------
    open_dialog_bank(type) {
      console.log(this.selected_bank_id);
      console.log(this.form.costSource);
      switch (type) {
        case "cost":
          this.bank_type = "20";
          this.selected_bank_id = this.selected_bank_id_cost;
          break;
        case "to":
          if (this.form.costSource == 10) {
            this.bank_type = "30";
            this.selected_bank_id = this.selected_bank_id_supplie;
          }
          if (this.form.costSource == 20) {
            this.bank_type = "10";
            this.selected_bank_id = this.selected_bank_id_to;
          }
          if (this.form.costSource == 30) {
            this.bank_type = "40";
            this.selected_bank_id = this.selected_bank_id_other;
          }
          break;
        default:
          break;
      }
      this.dialog_if_bank = true;
    },
    bank_detail(item) {
      switch (this.bank_type) {
        case "20":
          this.selected_bank_id_cost = item.id;
          this.form.costBankId = item.id;
          this.form.costBankNo = item.bankNo;
          this.form.costBankName = item.bankName;
          this.form.costBankAccount = item.accountName;
          break;
        case "10":
          this.selected_bank_id_to = item.id;
          this.form.toBankId = item.id;
          this.form.toBankNo = item.bankNo;
          this.form.toBankName = item.bankName;
          this.form.toBankAccount = item.accountName;
          break;
        case "30":
          this.selected_bank_id_supplie = item.id;
          this.form.toBankId = item.id;
          this.form.toBankNo = item.bankNo;
          this.form.toBankName = item.bankName;
          this.form.toBankAccount = item.accountName;
          break;
        case "40":
          this.selected_bank_id_other = item.id;
          this.form.toBankId = item.id;
          this.form.toBankNo = item.bankNo;
          this.form.toBankName = item.bankName;
          this.form.toBankAccount = item.accountName;
          break;
        default:
          break;
      }
      this.bank_cancel();
    },
    bank_cancel() {
      this.dialog_if_bank = false;
    },
    // ----------------------------------------------------------
    // 選擇接待人詳細信息----------------------------------
    open_dialog_receiverName() {
      this.dialog_if_receiver = true;
    },

    receiver_detail(item) {
      this.selected_receiver_id = item.userId;

      this.form.operatorName = item.receiverName;
      this.form.operatorId = item.userId;

      this.dialog_if_receiver = false;
    },
    // 關閉彈窗客戶
    receiver_cancel() {
      this.dialog_if_receiver = false;
    },
    // ----------------------------------------------------------
    // 選擇供應商詳細信息----------------------------------
    open_dialog_supplierName() {
      this.dialog_if_supplier = true;
    },

    supplier_detail(item) {
      this.selected_supplier_id = item.id;

      this.form.supplierCode = item.supplierCode;
      this.form.supplierName = item.supplierName;

      this.dialog_if_supplier = false;
    },
    // 關閉彈窗客戶
    supplier_cancel() {
      this.dialog_if_supplier = false;
    },
    // ----------------------------------------------------------
    change_costSource(name) {
      this.form.toBankId = "";
      this.form.toBankNo = "";
      this.form.toBankName = "";
      this.form.toBankAccount = "";
    },
    /** 提交按钮 */
    submitForm(type) {
      // 提交時間
      this.form.costStatus = type;
      console.log(this.form);
      console.log(this.bizCostItemList);
      switch (this.form.costSource) {
        case "10":
          break;
        case "20":
          this.form.supplierCode = "";
          this.form.supplierId = "";
          this.form.supplierName = "";
          break;
        case "30":
          this.form.supplierCode = "";
          this.form.supplierId = "";
          break;
        default:
          break;
      }
      this.form.taxAmount = 0; //稅金
      this.form.costAmount = 0; //報價金額
      this.form.costTaxAmount = 0; // 含稅報價
      this.bizCostItemList.map((item) => {
        item.unitPrice = item.costAmount;
        this.form.costAmount += item.costAmount - 0;
        this.form.taxAmount += item.taxAmount - 0;
        this.form.costTaxAmount += item.costTaxAmount - 0;
      });

      this.form.bizCostItemList = this.bizCostItemList;

      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.btn_disable = true;
          updateCost(this.form)
            .then((response) => {
              setTimeout(() => {
                this.btn_disable = false;
              }, 1000);
              this.btn_disable = false;
              this.$modal.msgSuccess("修改成功");
              this.$tab.closePage().then(() => {
                // 执行結束的逻辑
                const obj = { path: "/cost/cost", name: "Cost" };
                this.$tab.refreshPage(obj);
              });
            })
            .catch((err) => {
              setTimeout(() => {
                this.btn_disable = false;
              }, 1000);
              console.log(err);
            });
        }
      });
    },
    cancel() {
      this.$tab.closePage().then(() => {
        // 执行結束的逻辑
        const obj = { path: "/cost/cost", name: "Cost" };
        this.$tab.refreshPage(obj);
      });
    },
    /** 費用明細序號--------------------------------------------------------- */

    /** 复选框选中數据 */
    SelectionChange(selection) {
      this.checkedList = selection.map((item) => item.index);
    },
    /** 發票明細序號 */
    rowItemIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 發票明細添加按钮操作 */
    handleAddBizInvoiceItem() {
      let obj = {};
      obj.costItem = "";
      obj.costAmount = "";
      obj.taxAmount = "";
      obj.costTaxAmount = "";
      obj.tax = this.form.tax;
      obj.quantity = 1;
      obj.uint = "個";
      obj.unitPrice = "";
      obj.remark = "";
      this.bizCostItemList.push(obj);
    },
    /** 發票明細删除按钮操作 */
    handleDeleteBizInvoiceItem() {
      if (this.checkedList.length == 0) {
        this.$modal.msgError("請先選擇要删除的發票明細數据");
      } else {
        const bizCostItemList = this.bizCostItemList;
        const checkedList = this.checkedList;
        this.bizCostItemList = bizCostItemList.filter(function (item) {
          return checkedList.indexOf(item.index) == -1;
        });
      }
    },
    // 計算金額
    amountSum(item) {
      this.bizCostItemList[item.index - 1].tax = this.form.tax;
      this.bizCostItemList[item.index - 1].taxAmount = this.computeTaxAmount(
        this.bizCostItemList[item.index - 1].costAmount,
        this.form.tax
      );
      this.bizCostItemList[item.index - 1].costTaxAmount =
        this.computecostTaxAmount(
          this.bizCostItemList[item.index - 1].costAmount,
          this.form.tax
        );
      this.$forceUpdate();
      this.bizCostItemList.splice(1, 0);
      console.log(this.bizCostItemList);
    },
    computeTaxAmount(costAmount, taxRate) {
      return (costAmount * taxRate).toFixed(2);
    },
    computecostTaxAmount(costAmount, taxRate) {
      return (costAmount * (1 + (taxRate - 0))).toFixed(2);
    },
    // 稅率變化
    taxRate_change() {
      this.bizCostItemList.map((item) => {
        item.tax = this.form.tax;
        item.taxAmount = this.computeTaxAmount(item.costAmount, this.form.tax);
        item.costTaxAmount = this.computecostTaxAmount(
          item.costAmount,
          this.form.tax
        );
      });
      console.log(this.bizCostItemList);
      this.$forceUpdate();
      this.bizCostItemList.splice(1, 0);
    },
  },
};
</script>
<style  >
.dialog-footer {
  width: 100%;
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
      